<template>
  <div style="padding: 5px 20px;">
    <br>
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="景区名称">
        <el-input v-model="listQuery.unit_name" placeholder="请输入景区名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">
          <template #icon>
            <el-icon><Search /></el-icon>
          </template>
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="TJCollectionForm">
          <template #icon>
            <el-icon><Edit /></el-icon>
          </template>
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格-->
    <el-table :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="景区ID" prop="jq_id" width="100"></el-table-column>
      <el-table-column label="景区名称" prop="jq_name"></el-table-column>
      <el-table-column label="景区所在地" prop="jq_city"></el-table-column>
      <el-table-column label="景区具体地址" prop="jq_address"></el-table-column>
      <el-table-column label="景区评级" prop="jq_rating"></el-table-column>
      <el-table-column label="景区类型" prop="jq_type"></el-table-column>
      <el-table-column label="对应问答对数量" prop="qa_count"></el-table-column>
      <el-table-column label="对应管理员" prop="responsible_admin"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button type="primary" circle @click="BJCollectionForm(scope.$index)">
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="danger" circle @click="deleteVisible(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                   :page-sizes="[10]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   :background="true">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
      <el-form ref="collectionform" :rules="rules" :model="ruleForm" label-width="120px" label-position="left">
        <el-form-item label="景区ID" prop="jq_id" v-if="dialogStatus=='create'">
          <el-input placeholder="景区ID" v-model="ruleForm.jq_id"></el-input>
        </el-form-item>
        <el-form-item label="景区名称" prop="jq_name">
          <el-input placeholder="景区名称" v-model="ruleForm.jq_name"></el-input>
        </el-form-item>
        <el-form-item label="景区所在地" prop="jq_city">
          <el-input placeholder="景区所在地" v-model="ruleForm.jq_city"></el-input>
        </el-form-item>
        <el-form-item label="景区具体地址" prop="jq_address">
          <el-input placeholder="景区具体地址" v-model="ruleForm.jq_address" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="景区评级" prop="jq_rating">
          <el-input placeholder="景区评级" v-model="ruleForm.jq_rating"></el-input>
        </el-form-item>
        <el-form-item label="景区类型" prop="jq_type">
          <el-input placeholder="景区类型" v-model="ruleForm.jq_type"></el-input>
        </el-form-item>
        <el-form-item label="对应问答对数量" prop="qa_count">
          <el-input placeholder="对应问答对数量" v-model="ruleForm.qa_count" type="number"></el-input>
        </el-form-item>
        <el-form-item label="对应管理员" prop="qa_count">
          <el-input placeholder="对应管理员" v-model="ruleForm.responsible_admin"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="submitCollectionForm('collectionform')">添 加</el-button>
        <el-button type="warning" v-else @click="updateCollectionForm('collectionform')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Edit, Clock, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

export default {
  name: 'ScenicSpots',
  components: {
    Search,
    Edit,
    Clock,
    Delete
  },
  mounted() {
    this.fetchData();
  },
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        unit_name: '',
      },
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '修改景区',
        create: '添加景区'
      },
      ruleForm: {
        jq_id: '',
        jq_name: '',
        jq_city: '',
        jq_address: '',
        jq_rating: '',
        jq_type: '',
        responsible_admin:'',
        qa_count: 0,
      },
      rules: {
        jq_id: [{
          required: true,
          message: '请输入景区ID',
          trigger: 'blur'
        }],
        jq_name: [{
          required: true,
          message: '请输入景区名称',
          trigger: 'blur'
        }],
        jq_city: [{
          required: true,
          message: '请输入景区所在地',
          trigger: 'blur'
        }],
        jq_address: [{
          required: true,
          message: '请输入景区具体地址',
          trigger: 'blur'
        }],
        jq_rating: [{
          required: true,
          message: '请输入景区评级',
          trigger: 'blur'
        }],
        jq_type: [{
          required: true,
          message: '请输入景区类型',
          trigger: 'blur'
        }],
        responsible_admin: [{
          required: true,
          message: '请输入对应管理员',
          trigger: 'blur'
        }],
        qa_count: [{
          required: true,
          message: '请输入对应问答对数量',
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      axios.get('http://127.0.0.1:8000/qa/scenic-spots/', {
        params: {
          page: this.listQuery.page,
          limit: this.listQuery.limit,
          keyword: this.listQuery.unit_name
        }
      }).then(response => {
        this.listLoading = false;
        this.list = response.data.results;
        this.total = response.data.count;
      }).catch(error => {
        console.error('Error fetching data:', error);
        this.listLoading = false;
      });
    },
    TJCollectionForm() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        console.log('dialogFormVisible:', this.dialogFormVisible);
      });
    },
    resetForm() {
      this.ruleForm = {
        jq_id: '',
        jq_name: '',
        jq_city: '',
        jq_address: '',
        jq_rating: '',
        jq_type: '',
        qa_count:'',
      };
    },
    BJCollectionForm($index) {
      this.ruleForm = JSON.parse(JSON.stringify(this.list[$index]));
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    submitCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.post('http://127.0.0.1:8000/qa/scenic-spotsadd/', this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('添加数据成功！');
          }).catch(error => {
            console.error('Error submitting data:', error);
            this.$message.error('添加数据失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
      updateCollectionForm(formname) {
        this.$refs[formname].validate((valid) => {
          if (valid) {
            axios.put(`http://127.0.0.1:8000/qa/scenic-spots/update/${this.ruleForm.jq_id}/`, this.ruleForm).then(response => {
              this.fetchData();
              this.dialogFormVisible = false;
              this.$message.success('修改数据成功！');
            }).catch(error => {
              console.error('Error updating data:', error);
              this.$message.error('修改数据失败！');
            });
          } else {
            console.log('error submit!');
            return false;
          }
        });
      },
      deleteVisible(scope) {
        const csrfToken = this.$cookies.get('csrftoken');
        if (!csrfToken) {
          console.error('CSRF token not found');
          this.$message.error('CSRF token not found');
          return;
        }

        this.$confirm(`确定要删除 ${scope.jq_id} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const url = `http://127.0.0.1:8000/qa/scenic-spots/delete/${scope.jq_id}/`;
          this.$axios.delete(url, { withCredentials: true, headers: { 'X-CSRFToken': csrfToken } })
            .then(response => {
              this.fetchData();
              this.$message.success('删除成功');
            })
            .catch(error => {
              console.error('Error:', error);
              this.$message.error('删除数据失败！请检查网络连接或重试。');
              if (error.response && error.response.status === 403) {
                this.$message.error('CORS 策略阻止了请求。请检查后端配置。');
              }
            });
        }).catch(() => {
          // 用户取消删除
        });
      },
      formatDateTime(dateTime) {
        if (!dateTime) return '';
        const date = new Date(dateTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
    }
  }
</script>
<style>
.answer-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>
